import {onMounted, onUnmounted, ref, watch} from 'vue'
import {useWebConfigStore} from '@/stores/modules/webConfig.store'

/**
 * 切换深色模式
 * @param val
 */
export const updateHtmlDarkClass = (val: boolean) => {
	const htmlEl = document.getElementsByTagName('html')[0]
	if (val) {
		htmlEl.classList.add('dark')
	} else {
		htmlEl.classList.remove('dark')
	}
}

/**
 * 切换当前页面的深色模式
 */
export const togglePageDark = (val: boolean) => {
	const webConfigStore = useWebConfigStore()
	const isDark = ref(webConfigStore.layout.isDark)
	onMounted(() => {
		if (isDark.value !== val) updateHtmlDarkClass(val)
	})
	onUnmounted(() => {
		updateHtmlDarkClass(isDark.value)
	})
	watch(
			() => webConfigStore.layout.isDark,
			(newVal) => {
				isDark.value = newVal
				if (isDark.value !== val) updateHtmlDarkClass(val)
			}
	)
}
